/**
 * Copyright (C) Syerit Interactive 2010. All rights reserved. 
 */
package syerit.core.utils
{
	/**
	 * 
	 * @author Pavel Jacko syerit.com
	 * 
	 */	
	public class IdGenerator
	{
		public static function getID(prefix:String,checkAgainst:Array):String
		{
			var increment:int = 0;
			var newId:String;
			var isFree:Boolean = false;
			while(!isFree)
			{
				isFree = true;
				newId = prefix + "_" + increment;
				for each(var o:Object in checkAgainst)
				{
					if(o.id == newId)
					{
						isFree = false;
						break;
					}
				}
				if(isFree)
				{
					return newId;
				}
				isFree = false;
				increment++;
			}
			return null;
			 
		}
		
		public static function getTemplateID(prefix:String,checkAgainst:Array):String
		{
			var increment:int = 0;
			var newId:String;
			
			newId = prefix + "_" + increment
			while(hasId(newId,checkAgainst))
			{
				increment++;
				newId = prefix + "_" + increment;
			}
			
			return newId;
			
		}
		
		private static function hasId(id:String,source:Array):Boolean
		{
			for each(var o:Object in source)
			{
				if(o.id == id)
				{
					return true;
					break;
				}
				if(o.children)
				{
					if(hasId(id,o.children))
					{
						return true;
						break;
					}
				}
			}
			return false;
		}
	}
}